package com.wqs.tool.datainit.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;
import org.apache.commons.beanutils.RowSetDynaClass;

/**
 * 
 * @author ALEX
 *
 */
public class JdbcUtils {
	
	
	
	
	/**
	 * 获得数据库连接
	 * @param driverClassName
	 * @param url
	 * @param username
	 * @param password
	 * @return
	 */
	public static Connection getConnection(String driverClassName,String url,String username ,String password) {
		//获得连接数据库连接
        Connection conn=null;
        try {
            //初始化Driver类，注册驱动
                Class.forName(driverClassName);
                //连接数据库
                conn= DriverManager.getConnection(url, username,password);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn; 
	}
	
	
	public static List<DynaBean> queryList(Connection con,String sql) {
		List<DynaBean> list = new ArrayList<DynaBean>();
		RowSetDynaClass rowSet = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = con.prepareStatement(sql);
			rs = pstm.executeQuery();
			rowSet = new RowSetDynaClass(rs,false,-1,true);
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			close(con,pstm,rs);
		}
		return rowSet == null ? null : rowSet.getRows();
	}
	
	
	
	/**
	 * 关闭数据库
	 * @param con
	 * @param pstem
	 * @param rs
	 */
	public static void close(Connection con,PreparedStatement pstem,ResultSet rs) {
		try {
            if(con!=null) {
            con.close();
            }
            if(pstem!=null)
            {
                pstem.close();
            }
            if(rs!=null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
	}

}
